<?php
/**
 * Web版数据库初始化器
 * 可以在浏览器中直接运行来创建数据库表
 */

// 数据库配置
$db_config = [
    'host' => 'localhost',
    'username' => 's6814949',
    'password' => 'xssx123456',  // 请根据您的MySQL配置修改
    'database' => 's6814949'
];

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库初始化 - 投注游戏</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
        .success { color: #4caf50; background: #e8f5e8; padding: 10px; border-radius: 5px; margin: 10px 0; }
        .error { color: #f44336; background: #ffeaea; padding: 10px; border-radius: 5px; margin: 10px 0; }
        .info { color: #2196f3; background: #e3f2fd; padding: 10px; border-radius: 5px; margin: 10px 0; }
        .config-form { background: #f9f9f9; padding: 20px; border-radius: 8px; margin: 20px 0; }
        input, button { padding: 8px; margin: 5px; }
        button { background: #4caf50; color: white; border: none; border-radius: 4px; cursor: pointer; }
        pre { background: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; }
    </style>
</head>
<body>
    <h1>投注游戏 - 数据库初始化</h1>
    
    <?php if (isset($_POST['init_database'])): ?>
        
        <?php
        // 更新配置
        $db_config['host'] = $_POST['host'] ?? 'localhost';
        $db_config['username'] = $_POST['username'] ?? 'root';
        $db_config['password'] = $_POST['password'] ?? '';
        $db_config['database'] = $_POST['database'] ?? 's6814949';
        
        try {
            // 连接MySQL（不指定数据库）
            $pdo = new PDO(
                "mysql:host={$db_config['host']};charset=utf8mb4",
                $db_config['username'],
                $db_config['password']
            );
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            echo "<div class='success'>✓ MySQL连接成功</div>";
            
            // 创建数据库
            $pdo->exec("CREATE DATABASE IF NOT EXISTS {$db_config['database']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            echo "<div class='success'>✓ 数据库 '{$db_config['database']}' 创建/确认完成</div>";
            
            // 选择数据库
            $pdo->exec("USE {$db_config['database']}");
            
            // 清理现有表
            $drop_sqls = [
                "SET FOREIGN_KEY_CHECKS = 0",
                "DROP TABLE IF EXISTS daily_profits",
                "DROP TABLE IF EXISTS transactions",
                "DROP TABLE IF EXISTS user_positions", 
                "DROP TABLE IF EXISTS price_history",
                "DROP TABLE IF EXISTS game_rounds",
                "DROP TABLE IF EXISTS users",
                "SET FOREIGN_KEY_CHECKS = 1"
            ];
            
            foreach ($drop_sqls as $sql) {
                $pdo->exec($sql);
            }
            echo "<div class='info'>✓ 清理旧表完成</div>";
            
            // 创建表
            $tables = [
                'users' => "CREATE TABLE users (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) UNIQUE NOT NULL,
                    password VARCHAR(255) NOT NULL,
                    balance DECIMAL(10,2) DEFAULT 1000.00,
                    frozen_profit DECIMAL(10,2) DEFAULT 0.00,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
                
                'game_rounds' => "CREATE TABLE game_rounds (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    round_number INT NOT NULL,
                    status ENUM('trading', 'settlement', 'break') DEFAULT 'trading',
                    start_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    end_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    settlement_price DECIMAL(8,2) DEFAULT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
                
                'price_history' => "CREATE TABLE price_history (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    round_id INT,
                    price DECIMAL(8,2) NOT NULL,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_round_id (round_id),
                    INDEX idx_timestamp (timestamp)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
                
                'user_positions' => "CREATE TABLE user_positions (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    round_id INT NOT NULL,
                    round_number INT NOT NULL,
                    quantity DECIMAL(10,4) NOT NULL,
                    purchase_price DECIMAL(8,2) NOT NULL,
                    purchase_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    is_active BOOLEAN DEFAULT TRUE,
                    INDEX idx_user_id (user_id),
                    INDEX idx_round_id (round_id),
                    INDEX idx_is_active (is_active)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
                
                'transactions' => "CREATE TABLE transactions (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    round_id INT NOT NULL,
                    type ENUM('buy', 'sell') NOT NULL,
                    quantity DECIMAL(10,4) NOT NULL,
                    price DECIMAL(8,2) NOT NULL,
                    amount DECIMAL(10,2) NOT NULL,
                    profit DECIMAL(10,2) DEFAULT 0.00,
                    transaction_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_user_id (user_id),
                    INDEX idx_round_id (round_id),
                    INDEX idx_transaction_time (transaction_time)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
                
                'daily_profits' => "CREATE TABLE daily_profits (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    profit_amount DECIMAL(10,2) NOT NULL,
                    earned_date DATE NOT NULL,
                    is_available BOOLEAN DEFAULT FALSE,
                    available_date DATE NOT NULL,
                    INDEX idx_user_id (user_id),
                    INDEX idx_available_date (available_date),
                    INDEX idx_is_available (is_available)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
            ];
            
            foreach ($tables as $table_name => $sql) {
                $pdo->exec($sql);
                echo "<div class='success'>✓ 创建表: {$table_name}</div>";
            }
            
            // 创建测试用户
            $users = [
                ['admin', password_hash('admin123', PASSWORD_DEFAULT)],
                ['player1', password_hash('123456', PASSWORD_DEFAULT)],
                ['player2', password_hash('123456', PASSWORD_DEFAULT)]
            ];
            
            foreach ($users as $user) {
                $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
                $stmt->execute($user);
                echo "<div class='success'>✓ 创建用户: {$user[0]}</div>";
            }
            
            // 创建初始游戏轮次
            $start_time = date('Y-m-d H:i:s');
            $end_time = date('Y-m-d H:i:s', strtotime('+15 minutes'));
            
            $stmt = $pdo->prepare("INSERT INTO game_rounds (round_number, status, start_time, end_time) VALUES (1, 'trading', ?, ?)");
            $stmt->execute([$start_time, $end_time]);
            $round_id = $pdo->lastInsertId();
            
            // 添加初始价格
            $stmt = $pdo->prepare("INSERT INTO price_history (round_id, price) VALUES (?, 100.00)");
            $stmt->execute([$round_id]);
            
            echo "<div class='success'>✓ 创建初始游戏轮次</div>";
            
            // 更新config/database.php
            $config_content = "<?php
// 数据库配置
define('DB_HOST', '{$db_config['host']}');
define('DB_USER', '{$db_config['username']}');
define('DB_PASS', '{$db_config['password']}');
define('DB_NAME', '{$db_config['database']}');

try {
    \$pdo = new PDO(\"mysql:host=\" . DB_HOST . \";dbname=\" . DB_NAME . \";charset=utf8mb4\", DB_USER, DB_PASS);
    \$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    \$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch(PDOException \$e) {
    die(\"数据库连接失败: \" . \$e->getMessage());
}

// 创建数据库表 - 仅在需要时调用
function createTables(\$pdo) {
    // 表已通过database_init.php创建
    return true;
}
?>";
            
            file_put_contents('config/database.php', $config_content);
            echo "<div class='success'>✓ 更新数据库配置文件</div>";
            
            echo "<div class='success'>";
            echo "<h3>🎉 初始化完成！</h3>";
            echo "<p><strong>测试账号：</strong></p>";
            echo "<ul>";
            echo "<li>管理员: admin / admin123</li>";
            echo "<li>玩家1: player1 / 123456</li>";
            echo "<li>玩家2: player2 / 123456</li>";
            echo "</ul>";
            echo "<p><a href='login.php' style='color: #4caf50; text-decoration: none; font-weight: bold;'>→ 立即登录游戏</a></p>";
            echo "</div>";
            
        } catch (PDOException $e) {
            echo "<div class='error'>❌ 错误: " . htmlspecialchars($e->getMessage()) . "</div>";
        }
        ?>
        
    <?php else: ?>
        
        <div class="info">
            <h3>数据库配置</h3>
            <p>请填写您的MySQL数据库配置信息：</p>
        </div>
        
        <form method="POST" class="config-form">
            <table>
                <tr>
                    <td><label for="host">数据库主机:</label></td>
                    <td><input type="text" id="host" name="host" value="<?php echo htmlspecialchars($db_config['host']); ?>" required></td>
                </tr>
                <tr>
                    <td><label for="username">用户名:</label></td>
                    <td><input type="text" id="username" name="username" value="<?php echo htmlspecialchars($db_config['username']); ?>" required></td>
                </tr>
                <tr>
                    <td><label for="password">密码:</label></td>
                    <td><input type="password" id="password" name="password" value="<?php echo htmlspecialchars($db_config['password']); ?>"></td>
                </tr>
                <tr>
                    <td><label for="database">数据库名:</label></td>
                    <td><input type="text" id="database" name="database" value="<?php echo htmlspecialchars($db_config['database']); ?>" required></td>
                </tr>
            </table>
            <br>
            <button type="submit" name="init_database">开始初始化数据库</button>
        </form>
        
        <div class="info">
            <h4>说明：</h4>
            <ul>
                <li>如果数据库不存在，系统会自动创建</li>
                <li>如果表已存在，将会重新创建（数据会丢失）</li>
                <li>初始化完成后会创建3个测试账号</li>
                <li>建议在生产环境前备份现有数据</li>
            </ul>
        </div>
        
    <?php endif; ?>
    
    <hr>
    <p><small>如果遇到问题，可以手动执行 <code>database_setup.sql</code> 文件中的SQL语句。</small></p>
</body>
</html>
